<template>
	<div class="goods">
		<el-row class="searchForm" v-if="showSearch">
			<el-col>
				<el-form
					ref="searchForm"
					:model="searchForm"
					status-icon
					label-width="130px"
					size="mini"
					:inline="true"
				>
					<el-form-item label="农产品名称" prop="categoryName" class="form-item">
						<el-input
							v-model.trim="searchForm.goodsName"
							placeholder="请输入农产品名称"
							class="form-input"
						></el-input>
					</el-form-item>
					<el-form-item label="农产品序列号" prop="categoryNum" class="form-item">
						<el-input
							v-model.trim="searchForm.goodsNum"
							placeholder="请输入农产品序列号"
							class="form-input"
						></el-input>
					</el-form-item>
					<el-form-item label="状态" prop="status" class="form-item">
						<el-select v-model="searchForm.status" placeholder="农产品状态" clearable>
							<el-option
								v-for="item in statusOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value"
								class="form-input"
							>
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="产品所属分类" prop="categoryId" class="form-item">
						<el-select
							v-model="searchForm.categoryId"
							placeholder="产品所属农产品"
							clearable
						>
							<el-option
								v-for="item in categoryOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value"
								class="form-input"
							>
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="最小价格" prop="minPrice" class="form-item">
						<el-input-number
							v-model="searchForm.minPrice"
							:precision="2"
							:step="0.1"
							placeholder="最小价格"
						></el-input-number>
					</el-form-item>
					<el-form-item label="最大价格" prop="maxPrice" class="form-item">
						<el-input-number
							v-model="searchForm.maxPrice"
							:precision="2"
							:step="0.1"
							placeholder="最大价格"
						></el-input-number>
					</el-form-item>
					<el-form-item
						label="产品所属商家编号"
						prop="shopId"
						class="form-item"
						v-if="$store.state.user.admin"
					>
						<el-input
							v-model.number="searchForm.shopId"
							placeholder="所属商家编号"
						></el-input>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>

		<el-row style="padding-bottom: 20px">
			<el-col :push="1" :span="23">
				<el-button type="primary" size="mini" icon="el-icon-search" @click="search"
					>搜索</el-button
				>
				<el-button
					size="mini"
					icon="el-icon-refresh"
					@click="resetForm('searchForm')"
					v-if="showSearch"
					>重置
				</el-button>
			</el-col>
		</el-row>

		<el-row>
			<el-col :push="1" :span="20">
				<el-button plain type="primary" size="mini" icon="el-icon-plus" @click="create"
					>新增
				</el-button>
				<el-button
					size="mini"
					plain
					type="success"
					icon="el-icon-scissors"
					@click="update"
					:disabled="checkedIds.length != 1"
					>修改
				</el-button>
				<el-button
					size="mini"
					plain
					type="danger"
					icon="el-icon-delete-solid"
					@click="remove"
					:disabled="checkedIds.length == 0"
					>删除
				</el-button>
			</el-col>

			<el-col :push="1" :span="2">
				<el-tooltip effect="dark" content="隐藏搜索" placement="top">
					<el-button
						size="mini"
						circle
						icon="el-icon-search"
						@click="showSearch = !showSearch"
					>
					</el-button>
				</el-tooltip>
				<el-tooltip effect="dark" content="刷新" placement="top">
					<el-button size="mini" circle icon="el-icon-refresh" @click="refresh">
					</el-button>
				</el-tooltip>
				<el-tooltip effect="dark" content="隐藏列" placement="top">
					<el-button
						size="mini"
						circle
						icon="el-icon-menu"
						@click="showHidCol = !showHidCol"
					>
					</el-button>
				</el-tooltip>
				<el-popover width="60" placement="bottom" trigger="click" v-model="showHidCol">
					<el-checkbox-group v-model="checkedColumns">
						<el-checkbox v-for="column in columns" :label="column" :key="column">
						</el-checkbox>
					</el-checkbox-group>
				</el-popover>
			</el-col>
		</el-row>

		<el-row>
			<el-table
				ref="multipleTable"
				:data="list"
				tooltip-effect="dark"
				max-height="510"
				style="width: 100%"
				@selection-change="handMulSelect"
			>
				<el-table-column type="selection"> </el-table-column>
				<el-table-column type="expand" fixed>
					<template slot-scope="scope">
						<el-card
							v-for="item in scope.row.goodsImgVos"
							shadow="always"
							:key="item.imgId"
							style="width: 150px; height: 150px"
						>
							<div class="clearfix" style="width: 100px; padding-bottom: 5px">
								<el-button
									style="float: right; padding: 3px 0"
									type="text"
									@click="removeGoodsImg({ ...item, goodsId: scope.row.goodsId })"
									>点我删除</el-button
								>
							</div>
							<img
								:src="item.imgUrl"
								@click="openImgDialog(item.imgUrl)"
								width="100"
								height="100"
							/>
						</el-card>
					</template>
				</el-table-column>
				<el-table-column
					prop="goodsId"
					label="农产品编号"
					v-if="$Tool.findEle('农产品编号', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					show-overflow-tooltip
					prop="goodsName"
					label="农产品名称"
					v-if="$Tool.findEle('农产品名称', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					show-overflow-tooltip
					prop="goodsNum"
					label="序列码"
					v-if="$Tool.findEle('序列码', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="price"
					label="价格"
					v-if="$Tool.findEle('价格', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="balance"
					label="库存数量"
					v-if="$Tool.findEle('库存数量', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					show-overflow-tooltip
					label="所属分类"
					v-if="$Tool.findEle('所属分类', checkedColumns)"
				>
					<template slot-scope="scope">
						{{ handlerCategorys(scope.row.categoryVos) }}
					</template>
				</el-table-column>
				<el-table-column
					prop="status"
					label="状态"
					v-if="$Tool.findEle('状态', checkedColumns)"
				>
					<template slot-scope="scope">
						<el-switch
							v-model="scope.row.status"
							@click.native="changeStatus(scope.row)"
							active-value="0"
							inactive-value="1"
						>
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column
					prop="createTime"
					label="创建时间"
					v-if="$Tool.findEle('创建时间', checkedColumns)"
				>
				</el-table-column>
				<el-table-column label="操作" fixed="right">
					<template slot-scope="scope">
						<el-row>
							<el-button
								@click.native.prevent="updateOne(scope.row)"
								type="text"
								icon="el-icon-scissors"
								size="small"
							>
								修改
							</el-button>
							<el-button
								@click.native.prevent="removeOne(scope.row.goodsId)"
								type="text"
								icon="el-icon-delete-solid"
								size="small"
							>
								删除
							</el-button>
						</el-row>
					</template>
				</el-table-column>
			</el-table>
		</el-row>

		<el-row type="flex" justify="center" style="padding-top: 20px">
			<el-col :span="6">
				<el-pagination
					background
					@size-change="handlePageSize"
					@current-change="handlePage"
					:current-page="searchForm.page"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="searchForm.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="listTotal"
				>
				</el-pagination>
			</el-col>
		</el-row>

		<el-dialog :title="dialogTitle" :visible.sync="showDialog" width="40%">
			<el-form
				:model="submitForm"
				:rules="submitRules"
				ref="submitForm"
				label-width="6.25rem"
				inline
				class="submit-form"
			>
				<el-form-item label="图片列表" prop="imgUrls" class="form-item">
					<el-upload
						drag
						action="/upload/goods/img"
						accept="image/*"
						:auto-upload="false"
						:file-list="fileList"
						:on-change="fileChange"
						:on-remove="fileRemove"
						:on-preview="filePreview"
						:on-exceed="fileUploadExceed"
						:limit="3"
					>
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
					</el-upload>
				</el-form-item>
				<el-form-item label="产品分类" prop="categoryIds" required class="form-item">
					<el-select
						v-model="submitForm.categoryIds"
						clearable
						multiple
						filterable
						allow-create
						default-first-option
						placeholder="请选择分类标签"
						:multiple-limit="2"
					>
						<el-option
							v-for="item in categoryOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="农产品名称" prop="goodsName" required class="form-item">
					<el-input
						clearable
						v-model="submitForm.goodsName"
						placeholder="农产品名称(1-30位)"
					></el-input>
				</el-form-item>
				<el-form-item label="所属商家编号" prop="shopId" class="form-item" required>
					<el-input
						clearable
						v-model.number="submitForm.shopId"
						placeholder="所属商家编号"
					></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="status" class="form-item">
					<el-radio-group v-model="submitForm.status">
						<el-radio label="0">正常</el-radio>
						<el-radio label="1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="价格" prop="price" required class="form-item">
					<el-input-number
						clearable
						v-model.number="submitForm.price"
						placeholder="价格"
						:precision="2"
						:step="0.1"
						:min="1"
					></el-input-number>
				</el-form-item>
				<el-form-item label="库存数量" prop="balance" required class="form-item">
					<el-input-number
						clearable
						v-model.number="submitForm.balance"
						placeholder="库存数量"
						:step="10"
						:min="1"
					></el-input-number>
				</el-form-item>
				<el-form-item label="产品描述" prop="description" class="form-item">
					<el-input
						class="form-textarea"
						type="textarea"
						clearable
						v-model="submitForm.description"
						placeholder='请输入内容(描述之间,以"|"分割) '
						maxlength="255"
						show-word-limit
						:rows="4"
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="showDialog = false">取 消</el-button>
				<el-button type="primary" @click="submit(dialogTitle)">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="imgDialog.show" append-to-body>
			<img width="100%" :src="imgDialog.url" alt="无法显示" />
		</el-dialog>
	</div>
</template>

<script>
import { submitRules } from "@/utils/rules/goods"
import {
	getAllGoods,
	updateGoods,
	createGoods,
	removeGoods,
	removeGoodsImg,
	updateGoodsStatus,
} from "@/api/system/goods"
import { getAllCategory } from "@/api/system/category"
import { uploadGoodsImg } from "@/api/upload"
import { statusOptions } from "@/constants"
import { columns } from "@/constants/goods"

export default {
	name: "FrontMeGoods",
	data() {
		return {
			fileList: [],

			imgDialog: {
				show: false,
				url: "",
			},

			showDialog: false,
			dialogTitle: "",

			checkedColumns: columns,
			columns: columns,
			showHidCol: false,
			showSearch: true,
			searchForm: {
				goodsName: "",
				goodsNum: "",
				categoryId: null,
				status: "",
				shopId: null,
				minPrice: "",
				maxPrice: "",
				page: 1,
				pageSize: 10,
			},
			statusOptions: statusOptions,
			categoryOptions: [],
			list: [
				{
					goodsId: 1,
					goodsName: "精品黄瓜",
					goodsNum: "qweqhxiuiuiouiuoi",
					price: 20.2,
					balance: 500,
					categoryIds: [],
					status: "0",
					createTime: "2023-20-14 8:20:30",
				},
			],
			listTotal: 0,
			checkedIds: [],
			checkedItems: [],

			submitForm: {
				shopId: null,
				status: "0",
				goodsName: "",
				price: "",
				description: "",
				categoryIds: [],
				balance: 0,
				imgUrls: [],
			},
		}
	},
	computed: {
		submitRules,
	},
	mounted() {
		this.get()
		this.getAllCategory()
	},

	methods: {
		removeGoodsImg(item) {
			this.confirm(
				this.$confirm,
				`您是否确认删除农产品编号为"${this.$Tool.handlerLongStr(
					item.goodsId.toString()
				)}"下面的"${item.imgId}"编号图片`,
				async () => {
					let data = {
						imgIds: [item.imgId],
					}
					let res = await removeGoodsImg(data)
					if (res.code == 200) {
						this.refresh()
					}
				}
			)
		},
		fileRemove(file, fileList) {
			this.fileList = fileList
		},
		fileChange(file, fileList) {
			this.fileList = fileList
		},

		handlerCategorys(nlist) {
			let list = nlist.map((item) => {
				return item.categoryName
			})
			let str = ""
			for (let i = 0; i < list.length; i++) {
				if (i != list.length - 1) {
					str += list[i] + ","
				} else {
					str += list[i]
				}
			}
			return str
		},
		async getAllCategory() {
			let res = await getAllCategory({ page: 1, pageSize: 100 })
			if (res.code == 200) {
				let list = res.data
				let resList = []
				for (let i = 0; i < list.length; i++) {
					let res = {
						value: list[i].categoryId,
						label: list[i].categoryName,
					}
					resList.push(res)
				}
				this.categoryOptions = resList
			}
		},
		filePreview({ raw: file }) {
			this.openImgDialog(URL.createObjectURL(file))
		},
		openImgDialog(imgUrl) {
			this.imgDialog.show = true
			this.imgDialog.url = imgUrl
		},
		closeImgDialog() {
			this.imgDialog.show = false
			this.imgDialog.url = ""
		},

		fileUploadExceed() {
			this.$message.warning("上传图片数限制3张!")
		},
		async submitGoodsImg(fileList) {
			let list = fileList.map((item) => item.raw)

			if (!this.$Tool.checkList(list, this.checkFile)) {
				return false
			}

			let data = new FormData()
			list.forEach((file) => {
				data.append("file", file)
			})
			let res = await uploadGoodsImg(data)
			if (res.code == 200) {
				this.submitForm.imgUrls.push(...res.data.imgUrls)
				return true
			} else {
				return false
			}
		},

		checkFile(file) {
			const isJPng = file.type === "image/jpeg" || file.type == "image/png"
			const isLt2M = file.size / 1024 < 800
			if (!isJPng) {
				this.$message.error("上传农产品图片只能是 jpg/png 格式!")
				return isJPng
			}
			if (!isLt2M) {
				this.$message.error("上传农产品图片大小不能超过 800kb!")
				return isLt2M
			}
			return true
		},
		search() {
			this.get()
		},
		create() {
			this.openFormDialog("新增农产品")
		},
		categoryVoConvertCategoryIds(submitForm) {
			let list = [...submitForm.categoryVos]
			submitForm.categoryIds = list.map((item) => item.categoryId)
		},
		update() {
			this.submitForm = { ...this.checkedItems[0] }
			this.convertCategoryId(this.submitForm)
			this.openFormDialog("修改农产品")
		},
		async get() {
			let search = { ...this.searchForm }
			let res = await getAllGoods(this.$Tool.removeNullFiled(search))
			if (res.code == 200) {
				this.list = res.data
				this.listTotal = res.total
			}
		},

		openFormDialog(title) {
			this.showDialog = true
			this.dialogTitle = title
		},

		closeFormDialog() {
			this.resetForm("submitForm")
			this.showDialog = false
			this.dialogTitle = ""
		},

		async submit(title) {
			if (this.checkForm(this, "submitForm")) {
				let end = true
				if (this.fileList.length > 0) {
					end = await this.submitGoodsImg(this.fileList)
				}

				if (end) {
					if (title == "新增农产品") {
						this.submitCreate(title)
					} else if (title == "修改农产品") {
						this.submitUpdate(title)
					}
				}
			}
		},
		changeStatus(item) {
			let { goodsId, status } = item
			let str = status == "1" ? "禁用" : "启用"
			this.handConfirm(
				str,
				goodsId,
				async () => {
					let res = await updateGoodsStatus({ goodsId, status })
					if (res.code == 200) {
						this.refresh()
					} else {
						item.status = status == "1" ? "0" : "1"
					}
				},
				() => {
					item.status = status == "1" ? "0" : "1"
				}
			)
		},
		async submitUpdate(title) {
			let res = await updateGoods(this.submitForm)
			if (res.code == 200) {
				this.refresh()
				this.closeFormDialog()
			} else {
				this.openFormDialog(title)
			}
		},

		async submitCreate(title) {
			let res = await createGoods(this.submitForm)
			if (res.code == 200) {
				this.refresh()
				this.closeFormDialog()
			} else {
				this.openFormDialog(title)
			}
		},
		remove() {
			let goodsIds = this.checkedIds
			this.handConfirm("删除", goodsIds, async () => {
				let res = await removeGoods({ goodsIds })
				if (res.code == 200) {
					this.refresh()
				}
			})
		},
		refresh() {
			this.get()
		},

		updateOne(item) {
			this.submitForm = { ...item }
			this.convertCategoryId(this.submitForm)
			this.openFormDialog("修改农产品")
		},

		convertCategoryId(submitForm) {
			submitForm.imgUrls = []
			submitForm.categoryIds = submitForm.categoryVos.map((item) => item.categoryId)
			delete submitForm.categoryVos
		},
		removeOne(goodsId) {
			this.handConfirm("删除", goodsId, async () => {
				let goodsIds = [goodsId]
				let res = await removeGoods({ goodsIds })
				if (res.code == 200) {
					this.refresh()
				}
			})
		},
		resetForm(formName) {
			this.$Tool.objEmptyStr(this[formName], "page", "pageSize")
			this.$refs[formName].resetFields()
		},
		handMulSelect(list) {
			this.checkedIds = list.map((item) => item.goodsId)
			this.checkedItems = list
		},
		handlePageSize(val) {
			this.searchForm.pageSize = val
			this.refresh()
		},
		handlePage(val) {
			this.searchForm.page = val
			this.refresh()
		},

		handConfirm(text, data, success, error = () => {}) {
			this.confirm(
				this.$confirm,
				`您是否确认${text}农产品编号为"${this.$Tool.handlerLongStr(
					data.toString()
				)}"的数据项`,
				success,
				error
			)
		},
	},
}
</script>

<style lang="scss" scoped></style>
